package com.thingcom.delinrobot.main.adddevice;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseBackFragment;
import com.thingcom.delinrobot.utils.AppUtils;
import com.thingcom.delinrobot.utils.CommonDialog;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.PreferencesUtil;
import com.thingcom.delinrobot.utils.ToastUtil;
import com.thingcom.delinrobot.utils.WifiUtils;
import com.thingcom.delinrobot.view.SimpleToolbar;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//import static com.thingcom.delinrobot.main.adddevice.DeviceScanBackFragment.DEVICE_AP_NAME;

/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/15
 */
public class DeviceWifiBackFragment extends BaseBackFragment {

    @BindView(R.id.toolbar_wifi)
    SimpleToolbar toolbarWifi;
    @BindView(R.id.et_wifi_password)
    EditText etWifiPassword;


    static final String WIFI_NAME = "wifiName";
    static final String WIFI_PSW = "wifiPsw";
    @BindView(R.id.et_wifi_name)
    TextInputEditText etWifiName;
    @BindView(R.id.abc)
    TextInputLayout abc;
    @BindView(R.id.til_add_device_psw)
    TextInputLayout tilAddDevicePsw;
    @BindView(R.id.btn_wifi_continue)
    Button btnWifiContinue;


    public static DeviceWifiBackFragment newInstance() {
        Bundle bundle = new Bundle();
        DeviceWifiBackFragment fragment = new DeviceWifiBackFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WifiUtils.getInstance(getContext()).registBroadcast();
        WifiUtils.getInstance(getContext()).setWifiStateCallback(info -> {
            MyLog.i("收到wifi", "onWifiChange: " + info);
            etWifiName.setText(info);
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
            CommonDialog fragment = CommonDialog.newInstance(getString(R.string.start_tip), getString(R.string.open_position));
            fragment.setCancelable(false);
            if (getFragmentManager() != null) {
                fragment.show(getFragmentManager(), "dialog");
            }
            fragment.setOnOkListener((() -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }));
            fragment.setOnCancerListener((this::pop));
        }
    }

    //有些设备需要gps打开
    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) Objects.requireNonNull(getActivity()).getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }




    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_back_wifi, container, false);
        unbinder = ButterKnife.bind(this, view);
        btnWifiContinue.setEnabled(false);
        btnWifiContinue.setBackgroundColor(getResources().getColor(R.color.grey_button));
        ColorStateList colorStateList = getResources().getColorStateList(R.color.text_input_edit_selectoe);
        tilAddDevicePsw.setBoxStrokeColorStateList(colorStateList);
        abc.setBoxStrokeColorStateList(colorStateList);
        etWifiPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                //这个方法被调用，说明在s字符串中，从start位置开始的count个字符即将被长度为after的新文本所取代。
                // 在这个方法里面改变s，会报错。
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //这个方法被调用，说明在s字符串中，从start位置开始的count个字符刚刚取代了长度为before的旧文本。
                // 在这个方法里面改变s，会报错。

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (Objects.requireNonNull(etWifiName.getText()).toString().equals("<unknown ssid>") || TextUtils.isEmpty(etWifiPassword.getText().toString())){
                    btnWifiContinue.setEnabled(false);
                    btnWifiContinue.setBackgroundColor(getResources().getColor(R.color.grey_button));
                } else {
                    btnWifiContinue.setEnabled(true);
                    btnWifiContinue.setBackground(getResources().getDrawable(R.drawable.selector_button_main));
                }
                //这个方法被调用，那么说明s字符串的某个地方已经被改变。
            }
        });
        initToolbar(toolbarWifi);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        WifiUtils.getInstance(getContext()).unRegisterBroadcast();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @OnClick(R.id.btn_wifi_continue)
    public void onViewClicked() {
        AppUtils.hideSoftKeyboard(_mActivity);
        if (Objects.requireNonNull(etWifiName.getText()).toString().equals("<unknown ssid>") || TextUtils.isEmpty(etWifiPassword.getText().toString())) {
            ToastUtil.showToast(getContext(), getString(R.string.toast_wireless_wrong));
        } else {
            PreferencesUtil.getInstance(getContext()).putString(WIFI_NAME, etWifiName.getText().toString());
            PreferencesUtil.getInstance(getContext()).putString(WIFI_PSW, etWifiPassword.getText().toString());
            start(DeviceApOpenBackFragment.newInstance());
//            String ssid;

//            ssid = PreferencesUtil.getInstance(getContext()).getString(DEVICE_AP_NAME,"");
//            WifiUtils.getInstance(getContext()).connectWifiPws(ssid, "jielida123");
        }

    }
}
